<template>
  <div>
    <el-card
      v-if="!isShowTree"
      shadow="always"
      :body-style="{ padding: '20px' }"
    >
      <el-form
        size="small"
        style="margin-bottom: 10px"
        ref="form"
        label-width="80px"
        :inline="true"
      >
        <el-form-item size="small" label="">
          <el-input v-model="username"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="searchUserName"
            >查询</el-button
          >
          <el-button @click="Clear" size="small">清空</el-button>
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 20px">
        <el-button
          type="primary"
          size="small"
          @click="dialogVisible = true"
          v-btnPower="'btn.Role.add'"
          >添 加</el-button
        >
        <el-button
          type="danger"
          :disabled="tableSelect.length == 0"
          size="small"
          @click="batchDelete"
          v-btnPower="'btn.Role.remove'"
          >批量删除</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        :data="roleList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column width="80" label="序号" type="index">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" #default="{ row }">
          <el-input
            v-if="row.isIpt"
            v-model="roleName"
            size="mini"
            clearable
            @change=""
            v-btnPower="'btn.Role.assgin'"
          ></el-input>
          <span v-else>{{ row.roleName }}</span>
        </el-table-column>
        <el-table-column width="300" label="操作" #default="{ row }">
          <el-button
            type="info"
            size="mini"
            icon="el-icon-warning"
            @click="editAssign(row)"
            v-btnPower="'btn.Role.assgin'"
          ></el-button>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-check"
            v-btnPower="'btn.Role.update'"
            @click="saveRoleName(row)"
          ></el-button>

          <el-button
            v-if="!row.isIpt"
            type="primary"
            size="mini"
            icon="el-icon-edit-outline"
            v-btnPower="'btn.Role.update'"
            @click="editRoleName(row)"
          ></el-button>
          <el-button
            v-else
            type="primary"
            size="mini"
            @click="cancelRole(row)"
            v-btnPower="'btn.Role.remove'"
          >
            取消
          </el-button>
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            v-btnPower="'btn.Role.remove'"
            @click="deleteRole(row)"
          ></el-button>
        </el-table-column>
      </el-table>
      <el-pagination
        @current-change="setCurrent"
        @size-change="setSize"
        :page-sizes="[5, 6, 9]"
        :page-size="pagesize"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="30%">
      <div style="margin-bottom: 10px"><span>请输入新名称</span></div>
      <el-input v-model="addUserName" size="mini"></el-input>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <TreeModel :isShowTree="isShowTree" ref="treeModel"></TreeModel>
  </div>
</template>

<script>
import role from "@/api/acl/role";
import projectAPi from "@/api/project";
import { Message } from "element-ui";
import TreeModel from "./treeModel/index.vue";
export default {
  name: "BackgroundItemsIndex",

  data() {
    return {
      username: "",
      current: 1,
      pagesize: 5,
      total: 0,
      roleList: [],
      loading: false,
      // 控制添加角色显示
      dialogVisible: false,
      //要添加的角色名称
      addUserName: "",
      // table选中数据
      tableSelect: [],
      isShowTree: false,
      // 修改的名称
      roleName: "",
    };
  },

  mounted() {},
  methods: {
    // 清空
    Clear() {
      this.username = "";
      this.reqRoleList();
    },
    // 选中时触发
    handleSelectionChange(val) {
      this.tableSelect = [...val];
    },
    // 获取角色数据
    async reqRoleList(rolename = "") {
      this.loading = true;
      try {
        let { data } = await projectAPi.reqRoleList(
          this.current,
          this.pagesize,
          rolename
        );
        data.items.forEach((item) => {
          item.isIpt = false;
        });
        this.roleList = data.items;
        this.total = data.total;
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 修改当前页
    setCurrent(current) {
      this.current = current;
    },
    setSize(pagesize) {
      this.pagesize = pagesize;
    },
    // 查找username
    searchUserName() {
      this.reqRoleList(this.username);
    },
    // 保存角色
    async addRole() {
      try {
        await projectAPi.reqAddRole(this.addUserName);
        Message.success("保存成功");
      } catch (error) {
        Message.error(error);
      } finally {
        this.dialogVisible = false;
        this.reqRoleList();
      }
    },
    // 删除单个
    async deleteRole(role) {
      try {
        await this.$alert(`确定删除${role.roleName}`, "警告", {
          confirmButtonText: "确定",
          showCancelButton: "取消",
        });
        await projectAPi.deleteRole(role.id);
        Message.success("删除成功");
        this.reqRoleList();
      } catch (error) {
        if (error == "cancel") return;
        Message.error(error);
      }
    },
    // 批量删除
    async batchDelete() {
      try {
        await this.$alert(`确定删除吗`, "警告", {
          confirmButtonText: "确定",
          showCancelButton: "取消",
        });
        this.BATCHDELETE();
      } catch (error) {
        Message.error(error);
      }
    },
    // 批量删除确定
    async BATCHDELETE() {
      try {
        await Promise.all(
          this.tableSelect.map(async (item) => {
            try {
              await projectAPi.deleteRole(item.id);
            } catch (error) {
              Message.error(error);
            }
          })
        );
        Message.success("删除成功");
        this.reqRoleList();
      } catch (error) {}
    },
    // 修改权限
    editAssign(row) {
      this.$refs.treeModel.role = row;
      this.isShowTree = true;
    },
    // 修改role的name
    editRoleName(role) {
      this.roleName = role.roleName;
      role.isIpt = true;
    },
    // 确认修改
    async saveRoleName(role) {
      if (!role.isIpt) return;
      try {
        let Newrole = {
          ...role,
          originRoleName: role.roleName,
          roleName: this.roleName,
        };
        await projectAPi.reqSaveRoleName(Newrole);
        Message.success("修改成功");
      } catch (error) {
        Message.error(error);
      } finally {
        role.isIpt = false;
        this.reqRoleList();
      }
    },
    // 取消修改
    cancelRole(role) {
      role.isIpt = false;
    },
  },
  mounted() {
    this.reqRoleList();
    this.$bus.$on("TreeShow", (flag) => {
      this.isShowTree = flag;
    });
  },
  computed: {
    // 监听current和pagesize
    czChange() {
      let { current, pagesize } = this;
      return {
        current,
        pagesize,
      };
    },
  },
  watch: {
    // 监听current和pagesize
    czChange() {
      this.reqRoleList(this.username);
    },
  },
  components: {
    TreeModel,
  },
};
</script>

<style lang="scss" scoped></style>
